'''
Created on 2010-04-28

@author: AntoniKedracki
'''

import serial
import sys

class LightSnake(object):
    '''
    Controller for the JenkinsVector led modules.
    '''
    serialName = "COM1"
    serialPort = None
    channels = []

    def __init__(self, serialName, speed, channelNumber=96, debug=False):
        '''
        Constructor
        '''
        self.debug = debug
        if not self.debug:
            if type(serialName) != type(""):
                raise TypeError, "serialName must be a String, %s provided" % type(serialName)
            if type(channelNumber) != type(1):
                raise TypeError, "channelNumber must be a number, %s provided" % type(channelNumber)           
            self.serialName = serialName
            self.serialPort = serial.Serial(serialName, speed) #pylint: disable-msg=E1101,C0301
        
        self.channelNumber = channelNumber
        self.channels = [0] * channelNumber
        
    def set(self, channel, power):
        sys.stderr.write("Set channel %s to power %d\n" % (channel, power))
        if self.debug:
            return
        if channel >= self.channelNumber:
            raise AttributeError, "channelNumber out of scope (max is %s)" % self.channelNumber
        self.channels[channel] = power
        self.serialPort.write(chr(channel) + chr(254 if power == 255 else power) + chr(255))
        self.serialPort.flush()
        if self.serialPort.inWaiting() > 0:
            print self.serialPort.read(self.serialPort.inWaiting())
        
    def get(self, channel):
        if self.debug: 
            return "sorry no get in debug mode yet"
        return self.channels[channel]
